package synchronicity.util;

public class SchedulerUtil {
	public static Range getMeetingTime(long meetingLength, Range timeRange,
			RangeSet busyTimes) {
		if (meetingLength == 0) {
			throw new IllegalArgumentException(
					"Can't schedule a 0-length meeting!");
		}
		if (timeRange.getLength() == 0) {
			throw new IllegalArgumentException("Error: Time range is 0");
		}
		if (meetingLength > timeRange.getLength()) {
			throw new IllegalArgumentException(
					"Meeting length can not be longer than time range");
		}
		Range result = null;
		RangeSet subset = busyTimes.subset(timeRange);
		Range current, last;
		current = last = new Range(timeRange.getLeft(), timeRange
				.getLeft());
		for (int ii = 0; ii < subset.getRanges().size(); ii++) {
			current = (Range) subset.getRanges().elementAt(ii);
			// Check to the left of each range
			if (current.getLeft() - last.getRight() >= meetingLength) {
				result = new Range(last.getRight(), last.getRight()
						+ meetingLength);
				break;
			}
			last = current;
		}
		// check to the right of the last range
		if (result == null && current != null
				&& timeRange.getRight() - meetingLength >= current.getRight()) {
			result = new Range(current.getRight(), current.getRight()
					+ meetingLength);
		}
		return result;
	}
}
